import * as React from 'react'
import { isMemo } from 'react-is'

export function fillRef<T>(ref: React.Ref<T>, node: T) {
  if (typeof ref === 'function') {
    ref(node)
  } else if (typeof ref === 'object' && ref && 'current' in ref) { // 判断ref是否已被赋值
    (ref as any).current = node
  }
}

export function composeRef<T>(...refs: React.Ref<T>[]): React.Ref<T> {
  return (node: T) => {
    refs.forEach((ref: React.Ref<T>) => fillRef(ref, node))
  }
}

export function supportRef(nodeOrComponent: any) {
  const type = isMemo(nodeOrComponent) ? nodeOrComponent.type.type : nodeOrComponent.type

  if (typeof type === 'function' && !type.prototype?.render) {
    return false
  }

  if (typeof nodeOrComponent === 'function' && !nodeOrComponent.prototype?.render) {
    return false
  }
  return true
}